package com.sangeng.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户属性等参数要改为返回true
 * 不然会返回403 用户锁定
 */
@Data
public class LoginUser implements UserDetails {

    private User user;

    private List<String> permissions;

    public LoginUser() {
    }

    public LoginUser(User user) {
        this.user = user;
    }

    public LoginUser(List<String> permissions) {
        this.permissions = permissions;
    }

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /**
     * redis是不会把spring的类型系列化,为了安全,又因为LoginUser要进行系列化
     */
    //排除系列化
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authoritiesList;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        //方法一
//        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
//        permissions.forEach(s -> {
//            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(s);
//            authorities.add(simpleGrantedAuthority);
//        });
        if (null != authoritiesList) {
            return authoritiesList;
        }
        //方法二
        return authoritiesList = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
//        return authoritiesList;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
